#define _GNU_SOURCE 1
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <poll.h>
#include <libgen.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <cstring>
#define USER_LIMIT 5
#define BUFFER_SIZE 64
#define FD_LIMIT 65535

struct client_data
{
    sockaddr_in address;
    char *write_buf;
    char buf[BUFFER_SIZE] = {0};
};

int SetNonBlocking(int fd)
{
    int old_option = fcntl(fd, F_GETFL);
    int new_option = old_option | O_NONBLOCK;
    fcntl(fd, F_SETFL, new_option);
    return old_option;
}

int Add_Fd_To_Epoll(int epfd, int fd)
{
    epoll_event events;
    events.data.fd = fd;
    events.events = EPOLLIN;
    int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &events);
    assert(ret != -1);
}

int main(int argc, char **argv)
{
    if (argc <= 2)
    {
        printf("usage:%s ip_address port_number\n", basename(argv[0]));
        return 1;
    }
    const char *ip = argv[1];
    int port = atoi(argv[2]);
    int ret = 0;
    sockaddr_in address;
    address.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &address.sin_addr);
    address.sin_port = htons(port);
    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    assert(listenfd >= 0);
    ret = bind(listenfd, (sockaddr *)&address, sizeof(address));
    assert(ret != -1);
    ret = listen(listenfd, 5);
    assert(ret != -1);
    client_data *users = new client_data[FD_LIMIT];
    // 注册一个epoll
    int epfd = epoll_create(5);
    // 先把socket文件描述符注册进EPOLL
    Add_Fd_To_Epoll(epfd, listenfd);
    epoll_event events[USER_LIMIT + 1];
    int user_count = 0;
    // 等待事件发生
    while (1)
    {
        int num = epoll_wait(epfd, events, 65535, -1);
        for (int i = 0; i < num; i++)
        {
            if (events[i].data.fd == listenfd)
            {
                if (user_count >= USER_LIMIT)
                {
                    printf("客户端用户已经到达5，拒绝连接新的客户端！\n");
                    continue;
                }
                sockaddr_in client_addr;
                socklen_t client_addr_size = sizeof(client_addr);
                int clientfd = accept(listenfd, (sockaddr *)&client_addr, &client_addr_size);
                if (user_count >= USER_LIMIT)
                {
                    send(clientfd, "太多的客户端连接，请稍后再试！\n", sizeof("太多的客户端连接，请稍后再试！\n"), 0);
                    close(clientfd);
                    continue;
                }
                SetNonBlocking(clientfd);
                Add_Fd_To_Epoll(epfd, clientfd);
                users[clientfd].address = client_addr;
                user_count++;
                printf("来到了新的客户端，IP地址是：%s，port：%d", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
            }
            else if (events[i].data.fd && (EPOLLERR | EPOLLHUP))
            {
                printf("有客户端关闭！\n");
                close(events[i].data.fd);
                user_count--;
            }
            else if (events[i].events & EPOLLIN)
            {
                int bytes = recv(events[i].data.fd, users[events[i].data.fd].buf, 65535 - 1, 0);
                if (bytes > 0)
                {
                    users[events[i].data.fd].buf[bytes] = 0;
                    printf("收到了来自客户端：%s,端口号：%d的消息：%s\n", inet_ntoa(users[events[i].data.fd].address.sin_addr), ntohs(users[events[i].data.fd].address.sin_port), users[events[i].data.fd].buf);
                    // 转发所有消息给客户端（除了服务器）
                    for (int j = 0; j < FD_LIMIT; j++)
                    {
                        if (users[j].address.sin_port != 0 && j != events[i].data.fd)
                        {
                            epoll_event event;
                            event.data.fd = j;
                            event.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP | EPOLLERR;
                            epoll_ctl(epfd, EPOLL_CTL_MOD, j, &event);

                            // 设置要写入的数据
                            users[j].write_buf = users[events[i].data.fd].buf;
                        }
                    }
                }
            }
            else if (events[i].events & EPOLLOUT)
            {
                if (users[events[i].data.fd].write_buf)
                {
                    send(events[i].data.fd, users[events[i].data.fd].write_buf, strlen(users[events[i].data.fd].write_buf), 0);
                    users[events[i].data.fd].write_buf = NULL;

                    // 恢复只监听读事件
                    epoll_event event;
                    event.data.fd = events[i].data.fd;
                    event.events = EPOLLIN | EPOLLRDHUP | EPOLLERR;
                    epoll_ctl(epfd, EPOLL_CTL_MOD, events[i].data.fd, &event);
                }
            }
        }
    }

    return 0;
}